package com.jx.driving.request;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;

import com.jx.driving.message.TimeTerminalRequestMessage;
import com.jx.driving.protocol.terminal.annotation.ByteAnnotation;
import com.jx.driving.protocol.terminal.annotation.TailByteArrayAnnotation;
import com.jx.driving.protocol.terminal.annotation.TerminalAnnotation;
import com.jx.driving.protocol.terminal.codec.ClassReaderWriter;
import com.jx.driving.request.domain.TerminalInstruction;
import com.jx.driving.request.domain.TerminalInstruction1;
import com.jx.driving.request.domain.TerminalInstruction2;

/**
 * 终端控制
 * 
 * @author shenliuyang
 *
 *         2016年8月14日下午3:48:26
 */
@TerminalAnnotation
public class Terminal0x8105Request extends TimeTerminalRequestMessage {
	private static final long serialVersionUID = 2330725944818779015L;
	@ByteAnnotation(order = 1)
	private short cmd;// 命令字
	@TailByteArrayAnnotation(order = 2)
	private byte[] content;

	public short getCmd() {
		return cmd;
	}

	public void setCmd(short cmd) {
		this.cmd = cmd;
	}

	/**
	 * 获取终端参数
	 */
	public TerminalInstruction getInstruction() {
		Class<?> clazz = getInstructionClass();
		if (clazz == null) {
			return null;
		}
		try {
			ClassReaderWriter crw = new ClassReaderWriter(clazz);
			return crw.read(new ByteArrayInputStream(content));
		} catch (Exception ex) {
			throw new RuntimeException("读取终端指令异常", ex);
		}
	}

	/**
	 * 设置终端参数
	 */
	public void setInstruction(TerminalInstruction ins) {
		Class<?> clazz = getInstructionClass();
		if (clazz == null) {
			return;
		}
		try {
			ClassReaderWriter crw = new ClassReaderWriter(clazz);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			crw.write(out, ins);
			this.content = out.toByteArray();
		} catch (Exception ex) {
			throw new RuntimeException("写入终端指令异常", ex);
		}
	}

	private Class<? extends TerminalInstruction> getInstructionClass() {
		Class<? extends TerminalInstruction> insClass = null;
		switch (cmd) {
		case 1:
			insClass = TerminalInstruction1.class;
			break;
		case 2:
			insClass = TerminalInstruction2.class;
			break;
		default:
			break;
		}
		return insClass;
	}

	public byte[] getContent() {
		return content;
	}

	public void setContent(byte[] content) {
		this.content = content;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Terminal0x8105Request [cmd=").append(cmd).append(", content=").append(Arrays.toString(content))
				.append("]");
		return builder.toString();
	}

}
